package com.example.service;

import cn.hutool.core.util.StrUtil;
import com.example.common.CustomerException;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.mapper.AdminMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminService {

    @Resource
    AdminMapper adminMapper;

    public String admin(String admin) {
        if (admin.equals("admin")) {
            return "admin";
        } else {
            CustomerException customerException = new CustomerException();
            customerException.setMsg("账号或密码错误");
            customerException.setCode(500);
            throw customerException;
        }

    }

    public List<Admin> selectAll(Admin admin) {
        return adminMapper.selectAll(admin);
    }

    public PageInfo<Admin> selectPage(Integer pageNum, Integer pageSize, Admin admin) {
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> adminList = adminMapper.selectAll(admin);
        return PageInfo.of(adminList);
    }

    public void add(Admin admin) {
        Admin resadmin = adminMapper.selectByUsername(admin.getUsername());
        if  (resadmin != null) {
            throw new CustomerException(501,"账号重复");
        }
        if (StrUtil.isBlank(admin.getPassword())) {
            admin.setPassword("123456");
        }
        admin.setRole("ADMIN");
        adminMapper.insert(admin);
    }

    public void update(Admin admin) {
        adminMapper.updateById(admin);
    }

    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    public void deleteBatch(List<Admin> adminList) {
        for (Admin admin : adminList) {
            this.deleteById(admin.getId());
        }
    }

    public Admin login(Account account) {
        Admin dbadmin = adminMapper.selectByUsername(account.getUsername());
        if (dbadmin == null) {
            throw new CustomerException(501,"账号不存在");
        }
        if (!account.getPassword().equals(dbadmin.getPassword())) {
            throw new CustomerException(501,"账号或密码错误");
        }
        dbadmin.setToken(TokenUtils.createToken(dbadmin.getId()+"-ADMIN",dbadmin.getPassword()));
        return dbadmin;
    }

    public Admin selectById(String id) {
        return adminMapper.selectById(id);
    }

    public void updatePassword(Account account) {
        Admin dbadmin = adminMapper.selectById(account.getId().toString());
        dbadmin.setPassword(account.getPassword());
        adminMapper.updateById(dbadmin);
    }
}
